<template>
  <div>
    <el-button @click="tianjia">添加文章</el-button>
    <p></p>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="title" label=" 文章标题" width="180" />
      <el-table-column prop="xx.category_name" label=" 文章分类" width="180" />
      <el-table-column prop="state" label=" 发布状态" width="180" />
      <el-table-column prop="create_time" label=" 发布时间" />
      <el-table-column prop="xx.category_name" label="文章图片" width="180">
        <template #default="scope">
          <img
            :src="scope.row.cover_img"
            alt=" "
            style="width: 30px; height: 30px; border-radius: 5px"
          />
          {{ scope.row.category_name }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="deleteRow(scope.$index, scope.row)"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="dakaibianji(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page.pageNum"
      :page-size="page.pageSize"
      :page-sizes="[100, 200, 300, 400]"
      layout="total,  prev, pager, next, jumper"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加抽屉 -->
    <el-drawer
      v-model="drawer"
      title="添加文章"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 400px"
        ref="formRef"
        size="large"
      >
        <el-form-item>
          <el-input placeholder="请输入标题" v-model="form.title" />
        </el-form-item>
        <el-form-item>
          <div class="editor">
            <quill-editor
              theme="snow"
              contentType="html"
              v-model:content="form.content"
            >
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择分类">
          <el-select v-model="form.category_id" placeholder="请选择类别">
            <el-option
              v-for="item in cal"
              :key="item.id"
              :label="item.category_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="avatar-uploader-container" label="封面图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/user/shangchuan"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">添加</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 编辑抽屉 -->
    <el-drawer
      v-model="dra"
      title="编辑文章"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 400px"
        ref="formRef"
        size="large"
      >
        <el-form-item>
          <el-input placeholder="请输入标题" v-model="fm.title" />
        </el-form-item>
        <el-form-item>
          <div class="editor">
            <quill-editor
              theme="snow"
              contentType="html"
              v-model:content="fm.content"
            >
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-select v-model="fm.state" placeholder="请选择状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择分类">
          <el-select v-model="fm.category_id" placeholder="请选择类别">
            <el-option
              v-for="item in cal1"
              :key="item.id"
              :label="item.category_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="avatar-uploader-container" label="封面图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/user/shangchuan"
            :show-file-list="true"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl1" :src="imageUrl1" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onbianji()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { cuser } from "../stores/user.js"; // cuser 用于获取当前登录用户的相关信息
import { guanlicha, guanlishan, guanliadd, xiugai } from "../api/guanlis.js"; // 引入文章管理接口
import { ElMessage, ElMessageBox } from "element-plus"; // 引入提示框
import { QuillEditor } from "@vueup/vue-quill"; // 引入富文本编辑器
import "@vueup/vue-quill/dist/vue-quill.snow.css"; // 引入富文本编辑器样式
import { Plus } from "@element-plus/icons-vue"; // 引入图标
import type { UploadProps } from "element-plus";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue"; // 引入图标
import { reactive } from "vue"; //引入响应式
import { quanbiao } from "../api/login.js";

const drawer = ref(false); //添加抽屉
const uu = cuser(); //当前登录用户
const tableData = ref([]); // 表格数据
// 分页类
const page = ref({
  id: 0,
  total: 0, //总数
  pageNum: 1, //页码
  pageSize: 4, //每页条数
});

// 存放文章分类的集合
const cal = ref([]);
//文章管理查表方法
const into = async () => {
  uu.value = cuser().user;
  page.value.id = uu.value.id;
  const vv = await guanlicha(page.value);
  tableData.value = vv.data.list; // 更新表格数据
  page.value.total = vv.data.total;
};

// 分页
const handleSizeChange = (a) => {
  page.value.pageSize = a;
  console.log(`每页 ${a} 条`);
  into();
};
// 分页
const handleCurrentChange = (x) => {
  page.value.pageNum = x;
  console.log(`当前页: ${x}`);
  into();
};
// 删除按钮
const deleteRow = async (index, row) => {
  await guanlishan(row.id); // 假设 row 包含 id 属性
  ElMessageBox.confirm(
    // 提示用户是否删除
    "删除后数据将无法恢复,是否删除该数据?",
    "确定删除吗?",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning", // 提示类型
    }
  )
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      page.value.id = row.id;
      into(); // 重新获取数据
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
// 添加文章
const form = ref({});

const xinzeng = async () => {
  form.value.create_user = uu.user.id;
  const vv = await guanliadd(form.value);
  console.log(vv);
  if (vv.code == 20011) {
    ElMessage({
      type: "success",
      message: vv.msg,
    });
    into();
    drawer.value = false;
    form.value = {};
    form.valie.content = "";

  } else {
    ElMessage({
      type: "error",
      message: vv.mag,
    });
  }
};
const onSubmit = () => {
  console.log(form.value);
  xinzeng();
};
// 添加文章按钮
const tianjia = () => {
  drawer.value = true;
  quanbiao1();
};
const cal1 = ref([]);
// 文章分类查询
const quanbiao1 = async () => {
  const vv = await quanbiao(uu.user.id);
  if (vv.data.length == 0) {
    cal.value = [];
    ElMessage({
      type: "warning",
      message: "请先添加文章分类",
    });
  } else {
    cal1.value = vv.data;
    cal.value = vv.data;
  }
};
// 文章封面
const imageUrl = ref("");
// 文章封面后端返回的
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
  form.value.cover_img = response.data;
  console.log(response);
};
// 上传图片验证方法zheng
// 上传图片验证方法
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("图片上传必须是jpg/jpeg格式的图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
const imageUrl1 = ref("");
// 编辑按钮 打开抽屉
const dakaibianji = (row) => {
  dra.value = true;
  fm.value = row;
  imageUrl1.value = row.cover_img;
  quanbiao1();
};

//文章编辑
const dra = ref(false);
// 编辑表单
const fm = ref({});
// 编辑表单提交流程
const liucheng = async () => {
  const res = await xiugai(fm.value);
  console.log(res);
  if (res.code == 20031) {
    dra.value = false;
    into();
   
    ElMessage({
      type: "success",
      message: "修改成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "修改失败，请稍后再试",
    });
  }
};
// 编辑表单提交
const onbianji = () => {
  console.log(fm.value);
  liucheng();
   tableData.value.cover_img=imageUrl1.value;
};
const handleAvatarSuccess1: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl1.value = response.data;
  fm.value.cover_img = response.data;
  
  console.log(response);
};
import { useRouter } from 'vue-router'
const router = useRouter();
import {cs} from "../stores/zhuangtai.js";
const zt=cs()
// 页面加载时执行获取文章分类列表
onMounted(() => {
  if(zt.zhuangtai==""){
    ElMessage({
      message: "请先登录",
      type: "warning",
    });
    router.push("/")
  }
  into();
});
</script>

<style lang="scss" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
